﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HashTables
{
    class HashTable<TKey, TValue> where TKey : IComparable
    {
        LinkedList<KeyValuePair<TKey, TValue>>[] m_HashArray;
        
        public HashTable(uint initialSize)
        {
            m_HashArray = new LinkedList<KeyValuePair<TKey, TValue>>[initialSize];
        }

        int GetIndex(TKey key)
        {
            int test = Math.Abs(key.GetHashCode());
            return test % m_HashArray.Length;
        }

        int m_Count = 0;
        public int Count { get { return m_Count; } }

        public void Add(TKey key, TValue value)
        {
            m_Count++;

            int index = GetIndex(key);
            if (m_HashArray[index] == null)
            {
                m_HashArray[index] = new LinkedList<KeyValuePair<TKey, TValue>>();
            }

            m_HashArray[index].AddLast(new LinkedListNode<KeyValuePair<TKey, TValue>>(new KeyValuePair<TKey, TValue>(key, value)));
        }

        public void Remove(TKey key)
        { 
            int index = GetIndex(key);
            if (m_HashArray[index] == null)
                return;

            LinkedListNode<KeyValuePair<TKey, TValue>> node = m_HashArray[index].First;
            while (node != null)
            {
                LinkedListNode<KeyValuePair<TKey, TValue>> nextNode = node.Next;
                if (node.Value.Key.CompareTo(key) == 0)
                {
                    m_HashArray[index].Remove(node);
                }
                node = nextNode;
            }
        }

        public TValue Lookup(TKey key)
        {
            int index = GetIndex(key);
            if (m_HashArray[index] != null)
            {
                foreach (KeyValuePair<TKey, TValue> pair in m_HashArray[index])
                {
                    if (pair.Key.CompareTo(key) == 0)
                    {
                        return pair.Value;
                    }
                }
            }

            return default(TValue);
        }
    }
}
